package zy.wq.security.support;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;

import zy.wq.security.SystemUserPrincipal;
import zy.wq.security.bean.SystemUser;
import zy.wq.security.service.SystemUserService;



public class SystemUserAuthenticationProvider implements AuthenticationProvider{

	private SystemUserService systemUserService;
	private PasswordEncoder passwordEncoder;
	
	public SystemUserService getSystemUserService() {
		return systemUserService;
	}

	public void setSystemUserService(SystemUserService systemUserService) {
		this.systemUserService = systemUserService;
	}
	
	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		UsernamePasswordAuthenticationToken nap = (UsernamePasswordAuthenticationToken)authentication;
		SystemUser user = systemUserService.getUserByName(nap.getName());
		if(user == null) {
			throw new UsernameNotFoundException("");
		}
		String inputPassword = nap.getCredentials().toString();
		if(passwordEncoder == null) {
			if(!user.getPassword().equals(inputPassword)) {
				throw new BadCredentialsException("");
			}
		}else if(!passwordEncoder.matches(inputPassword, user.getPassword())) {
			throw new BadCredentialsException("");
		}
		checkUser(user);
		return createSuccessAuthentication(nap,user);
	}
	
	private void checkUser(SystemUser user) {
		
	}
	
	private Authentication createSuccessAuthentication(UsernamePasswordAuthenticationToken input,SystemUser user) {
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if(StringUtils.hasText(user.getRoles())) {
			for(String role : user.getRoles().split(",")) {
				authorities.add(new SimpleGrantedAuthority(role));
			}
		}
		return new UsernamePasswordAuthenticationToken(new SystemUserPrincipal(user), user.getPassword(),
				authorities);
	}

	@Override
	public boolean supports(Class<?> authentication) {
		return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
	}

}
